#define _CRT_SECURE_NO_WARNINGS

//数组中的逆序对--归并排序练习

class Solution {
public:
    vector<int> tmp;
    int reversePairs(vector<int>& nums) {
        return MergeSort(nums, 0, nums.size() - 1);
    }
    int MergeSort(vector<int>& nums, int left, int right)
    {
        if(left >= right) return 0;
        int ret = 0;
        //找中心点下标
        int mid = left + (right - left) / 2;
        //[left, mid] [mid + 1, right]
        ret += MergeSort(nums, left, mid);
        ret += MergeSort(nums, mid + 1, right);
        tmp.resize(nums.size());
        int i = 0, cur1 = left, cur2 = mid + 1;
        while(cur1 <= mid && cur2 <= right)
        {
            if(nums[cur1] > nums[cur2])
            {
                ret += mid - cur1 + 1;
                tmp[i++] = nums[cur2++];
            }             
            else 
                tmp[i++] = nums[cur1++];
        }
        while(cur1 <= mid) tmp[i++] = nums[cur1++];
        while(cur2 <= right) tmp[i++] = nums[cur2++];
        for(int j = left; j <= right; j++)
        {
            nums[j] = tmp[j - left];
        }
        return ret;
    }
};